<?php
/**
 * mdkeji_chatfree模块微站定义
 *
 * @author Mob990561601898
 * @url
 */
defined('IN_IA') or exit('Access Denied');

include_once IA_ROOT . "/addons/mdkeji_chatfree/core/functions.php";


if (!function_exists('M')) {
    function M($name)
    {
        static $model = array();
        if (empty($model[$name])) {
            include '../addons/mdkeji_chatfree/model/' . $name . '.mod.php';
            $model[$name] = new $name();
        }
        return $model[$name];
    }
}

class Mdkeji_chatfreeModuleSite extends WeModuleSite {

	public function __construct(){

		session_start();
		global $_W,$_GPC;

		if(empty($_SESSION['openid'])
		&&!empty($_COOKIE['openid'])){
			$_SESSION['openid']=$_COOKIE['openid'];
		}
	}

	public function doMobileIndex() {
		//这个操作被定义用来呈现 功能封面
		session_start();
		global $_W,$_GPC;
		$domain=M('domains')->get(array('Id'=>1));

		if(isset($_GET['nickName'])&&$domain['webregister']==1){
			$nickName=$_GET['nickName'];

			$userResult=M('user')->existNickName($nickName);
			if($userResult>0){
				$_SESSION['openid']=$userResult['openid'];
			}else{
				$openid=$this->create_guid();
				$nickName=$_GET['nickName'];
				$avatarUrl="http://".$_SERVER['HTTP_HOST']."/addons/mdkeji_chatfree/public/images/user/user".rand(1,70).".png";
				$password='123456';
				$timein=date("Y-m-d H:i:s");

				if(isset($openid)&&isset($nickName)&&isset($avatarUrl)&&isset($password)){

					$i=M("user")->insertUser(['openid'=>$openid,'password'=>$password,'avatarUrl'=>$avatarUrl,'nickName'=>$nickName,'timein'=>$timein]);
					if($i>0){
						$_SESSION['openid']=$openid;
					}

				}
			}
		}else{

			if ($_W['container'] == 'wechat') {
				if($_W['account']['level'] < 3){
					}else{
					$userinfo=mdkeji_oauth_userinfo($_W['uniacid']);
					if(!empty($userinfo)){

							$user=M('user')->getUser($userinfo['openid']);
							if(empty($user)){
								$time=date("Y-m-d H:i:s");

								$data = [
									'openid'=>$userinfo['openid'],
									'avatarUrl'=>$userinfo['headimgurl'],
									'nickName'=>$userinfo['nickname'],
									'timein'=>$time,
									'manager'=>0,
									'score'=>0,
								];
								$res=M('user')->insertUser($data);
								if($res>0){
									$_SESSION['openid']=$userinfo['openid'];
								}
							}else{
								$_SESSION['openid']=$userinfo['openid'];
							}


					}
				}

				}else{
				}


		}



	//生成cookie，腾讯微信浏览器不支持安卓端session跳转，丢失。
	if(!empty($_SESSION['openid'])){
		setcookie("openid", $_SESSION['openid'], time()+36000);
	}

		include $this->template("index");
	}
	public function doWebsetting() {
		//这个操作被定义用来呈现 管理中心导航菜单
		global $_W,$_GPC;

		//判断修改
		if($_W['ispost']){

			$data=array(
				"groupname"=>$_GPC['groupname'],
				"UIColor"=>$_GPC['UIColor'],
				"webregister"=>$_GPC['webregister'],
				"isshownotice"=>$_GPC['isshownotice'],
				"isshowpic"=>$_GPC['isshowpic'],
				"isshowemoji"=>$_GPC['isshowemoji'],
				"isshowvideo"=>$_GPC['isshowvideo'],
				"isshowmember"=>$_GPC['isshowmember']
			);
			M("domains")->update($data,array('Id'=>1));

			message('操作成功！', $this->createWebUrl('setting'),'success');
			exit;

		}
		$domain=M('domains')->get(array('Id'=>1));
		include $this->template("setting");
	}


	//生成唯一的id，官方
	public function create_guid($namespace = '') {
		static $guid = '';
		$uid = uniqid("", true);
		$data = $namespace;
		$data .= $_SERVER['REQUEST_TIME'];
		$data .= $_SERVER['HTTP_USER_AGENT'];
		$data .= $_SERVER['REMOTE_ADDR'];
		$data .= $_SERVER['REMOTE_PORT'];
		$hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
		$guid =
				substr($hash,  0,  8) .
				'-' .
				substr($hash,  8,  4) .
				'-' .
				substr($hash, 12,  4) .
				'-' .
				substr($hash, 16,  4) .
				'-' .
				substr($hash, 20, 12) ;
		return $guid;
	  }

	public function doMobilenickNameLogin(){

		session_start();
		$nickName=$_POST['nickName'];
		$domain=M("domains")->get(array('Id'=>1));
		if($domain['webregister']!=1)return;

			if(isset($nickName)){
				$userResult=M('user')->existNickName($nickName);
				if($userResult>0){
					$_SESSION['openid']=$userResult['openid'];
					return "OK";
				}else{
					$openid=$this->create_guid();
					$nickName=$_POST['nickName'];
					$avatarUrl="http://".$_SERVER['HTTP_HOST']."/addons/mdkeji_chatfree/public/images/user/user".rand(1,70).".png";
					$password='123456';
					$timein=date("Y-m-d H:i:s");

					if(isset($openid)&&isset($nickName)&&isset($avatarUrl)&&isset($password)){

						$i=M("user")->insertUser(['openid'=>$openid,'password'=>$password,'avatarUrl'=>$avatarUrl,'nickName'=>$nickName,'timein'=>$timein]);
						if($i>0){
							$_SESSION['openid']=$openid;
							return "OK";
						}

					}
				}
			}

	}

//关闭网页，自动清除后台的session
public function doMobileclearSession(){
	session_start();
	session_destroy();
	return "OK";
}

public function Json($data){
	header('Content-Type:application/json');
	return json_encode($data,JSON_UNESCAPED_UNICODE);
	// return stripslashes(json_encode($data,JSON_UNESCAPED_UNICODE));
}

public  function doMobilegetSessionLogin(){

	session_start();
	if(isset($_SESSION['openid'])){
		$openid=$_SESSION['openid'];
		$user=M("user")->getUser($openid);
		if(empty($user))return null;

			$user['roomName']='聊天室';
			$user['room_id']='room_1';

			return $this->Json($user);
	}else{
		return null;
	}

}

public function doMobilegetAllMember(){
	session_start();

	if(isset($_SESSION['openid'])){
		$user=M("user")->getAllMember();
		if(empty($user))return null;
		return $this->Json($user);
	}
}

//上传图片文件，返回图片网络地址url
public  function  doMobilesendimg(){

	if(!empty($_FILES['upimg'])&&($_FILES['upimg']['type']=='image/jpg'||$_FILES['upimg']['type']=='image/jpeg'
		||$_FILES['upimg']['type']=='image/gif'||$_FILES['upimg']['type']=='image/png')){
			$temp=explode("/",$_FILES['upimg']['type']);
			$extension=end($temp);

			$tmp=$_FILES['upimg']['tmp_name'];
			$imgpath=MODULE_ROOT.'/public/image/';
			$imgname=strtoupper(md5(uniqid(mt_rand(), true))).".".$extension;
			move_uploaded_file($tmp, $imgpath.$imgname);
			return  $imgname;
	}
}


//获取最近的50条消息
public function  doMobilegetmessage(){
	$much=$_GET['much'];
	$room_id=$_GET['room_id'];
	$msgtimes=$_GET['msgtimes']*$much;
	if(isset($room_id)&&isset($msgtimes)&&isset($much)){
		$msg30=M("rooms")->getMessage($room_id,$msgtimes,$much);
		return $this->Json($msg30);
	}
}

//下拉刷新，再次往上获取10条信息
public function  doMobilepullDownRefresh(){
	session_start();
	if(isset($_SESSION['openid'])){
		$msgsTopId=$_GET['msgsTopId'];
		$room_id=$_GET['roomIdNow'];
		$much=$_GET['much'];
		if(isset($msgsTopId)&&isset($room_id)&&isset($much)){
			$msg30=M('rooms')->pullDownRefresh($msgsTopId,$room_id,$much);
		return $this->Json($msg30);
		}
	}

}

public function doMobilesendAjax(){
	if($_POST["openid"]){
		$data=array(
			'openid'=>$_POST['openid'],
			'nickName'=>$_POST['nickName'],
			'avatarUrl'=>$_POST['avatarUrl'],
			'sendtype'=>$_POST['sendtype'],
			'msg'=>$_POST['msg'],
			'sendtime'=>date("Y-m-d H:i:s")
		);
		if(isset($_POST['saytowho'])){
			$data['saytowho']=$_POST['saytowho'];
		}
		M('rooms')->insertRoom_1($data);
	}
}

public function doMobilegetAjax(){
	$i=0;
	$max=60;
	if(!isset($_POST['msgtime'])){
		// print_r($_GPC);
		return;
	}

	$msgtime=$_POST['msgtime'];
	while(true){
		$i++;
		$msg=M('rooms')->getMessageRoom_1($msgtime);
		if(!empty($msg)){
			$msgend=end($msg);
			$data = [
                'status' => 1,
                'response_type' => 'is_read',
				'info' => $msg,
				'timenow'=>$msgend['sendtime']
			];
			return $this->Json($data);
            exit();
		}

		if($i>=$max){
			$data = [
                'status' => 1,
                'response_type' => 'is_connecting',
				'info' => '',
				'timenow'=>$msgtime
			];
			return $this->Json($data);
            exit();
		}

		usleep(100000);
	}
}

public function  doMobileexitLogin(){
	session_start();
	session_destroy();
	echo "已经退出，请重新进入！";
	die();
}






}